/**
 * 工作台页面
 */

import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Row,
  Col,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Space,
  Divider,
  message,
  Table,
  Popconfirm,
  Tooltip,
} from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import MmPixBox from "../components/MmPixBox";
import WorkbenchPlane from "./WorkbenchPlane";
import { ITStore } from "../../store";
import {
  ITWorkbench,
  ITColumns,
  ITWorkbenchSlot,
} from "../../store/interfaces";
type TProp = {
  store: ITStore;
};
const inputwide = {
  width: "100%",
};

const layout = {
  labelCol: { span: 13 },
  wrapperCol: { span: 11 },
};

const SearchAddComp: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
      workbenchStore: { changeShowAddEditWorkBenchModal },
    } = store;

    const handleClickAdd = () => {
      changeShowAddEditWorkBenchModal(true);
    };

    return (
      <Row style={{ marginBottom: 20 }}>
        <Col span={12}></Col>
        <Col span={12}>
          <Space wrap style={{ float: "right" }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleClickAdd}
            >
              {lang["langbuttonadd"]}
            </Button>
          </Space>
        </Col>
      </Row>
    );
  })
);

const AddEditWorkbenchModal: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
      workbenchStore: {
        showAddEditWorkBenchModal,
        changeShowAddEditWorkBenchModal,
        editWorkbenchData,
        addWorkbenchLoading,
        changeEditWorkbenchData,
        workbenchSlotlist,
        addWorkbench,
        getAllWorkbench,
        clearEditWorkbenchData,
        updateWorkbench,
      },
    } = store;

    const [form] = Form.useForm();

    useEffect(() => {
      if (editWorkbenchData) {
        form.setFieldsValue(editWorkbenchData);
      }
    }, [editWorkbenchData, form]);

    const close = () => {
      form.resetFields();
      clearEditWorkbenchData();
      changeShowAddEditWorkBenchModal(false);
    };

    const formFinish = async (values: ITWorkbench) => {
      let result = null;
      let msg: string = "";
      if (values.id) {
        // 编辑
        result = await updateWorkbench({
          ...values,
          slotList: workbenchSlotlist,
        });
        msg = lang["langmodifysuccess"];
      } else {
        // 新增
        const { id, ...addparam } = values;
        result = await addWorkbench({
          ...addparam,
          slotList: workbenchSlotlist,
        });
        msg = lang["langaddsuccess"];
      }
      if (!result) {
        close();
        message.success(msg);
        getAllWorkbench();
      } else {
        const { msg } = result;
        message.error(msg);
      }
    };

    const rowChange = (data: any) => {
      changeEditWorkbenchData({
        row: data,
      });
    };

    const rrowChange = (data: any) => {
      changeEditWorkbenchData({
        rrow: data,
      });
    };

    const columnChange = (data: any) => {
      changeEditWorkbenchData({
        column: data,
      });
    };

    const rcolumnChange = (data: any) => {
      changeEditWorkbenchData({
        rcolumn: data,
      });
    };

    return (
      <Modal
        title={
          <Row>
            <Col span={12}>
              {!!editWorkbenchData.id
                ? lang["langeditworkbench"]
                : lang["langaddworkbench"]}
            </Col>
            <Col span={11}>
              <Space style={{ float: "right" }}>
                <MmPixBox />
              </Space>
            </Col>
            <Col span={1}></Col>
          </Row>
        }
        open={showAddEditWorkBenchModal}
        destroyOnClose={true}
        onOk={() => {
          form.submit();
        }}
        width="90%"
        confirmLoading={addWorkbenchLoading}
        onCancel={close}
        forceRender
      >
        <Form
          {...layout}
          form={form}
          name="workbenchForm"
          onFinish={formFinish}
        >
          <Form.Item name="id" label="" hidden={true}>
            <Input />
          </Form.Item>
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item
                name="name"
                label={lang["langname"]}
                rules={[{ required: true }]}
              >
                <Input style={inputwide} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="row"
                label={`${lang["langrow"]}(${lang["langreagent"]})`}
                rules={[{ required: true }]}
              >
                <InputNumber style={inputwide} onChange={rowChange} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="column"
                label={`${lang["langcolumn"]}(${lang["langreagent"]})`}
                rules={[{ required: true }]}
              >
                <InputNumber style={inputwide} onChange={columnChange} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="rrow"
                label={`${lang["langrow"]}(${lang["langreaction"]})`}
                rules={[{ required: true }]}
              >
                <InputNumber style={inputwide} onChange={rrowChange} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="rcolumn"
                label={`${lang["langcolumn"]}(${lang["langreaction"]})`}
                rules={[{ required: true }]}
              >
                <InputNumber style={inputwide} onChange={rcolumnChange} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Divider />
        <WorkbenchPlane />
      </Modal>
    );
  })
);

// 工作台列表
const WorkbenchList: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
      workbenchStore: {
        getAllWorkbench,
        allWorkbenchLoading,
        allWorkbench,
        delWorkbenchLoading,
        delWorkbench,
        changeShowAddEditWorkBenchModal,
        changeEditWorkbenchData,
        changeWorkbenchSlotlist,
      },
    } = store;

    const [delData, setDelData] = useState<ITWorkbench | null>(null);

    useEffect(() => {
      getAllWorkbench();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const modifyItem = (record: ITWorkbench) => {
      changeWorkbenchSlotlist(record.slotList as ITWorkbenchSlot[]);
      changeEditWorkbenchData({ ...record });
      changeShowAddEditWorkBenchModal(true);
    };

    const deleteItem = async (record: ITWorkbench) => {
      setDelData(record);
      const { id } = record;
      const res = await delWorkbench({ id });
      if (!res) {
        getAllWorkbench();
        message.success(lang["langdeletesuccess"]);
        setDelData(null);
      }
    };

    const columns: ITColumns[] = [
      {
        title: lang["langname"],
        dataIndex: "name",
        key: "name",
      },
      {
        title: `${lang["langrow"]}(${lang["langreagent"]})`,
        dataIndex: "row",
        key: "row",
      },
      {
        title: `${lang["langcolumn"]}(${lang["langreagent"]})`,
        dataIndex: "column",
        key: "column",
      },
      {
        title: `${lang["langrow"]}(${lang["langreaction"]})`,
        dataIndex: "rrow",
        key: "rrow",
      },
      {
        title: `${lang["langcolumn"]}(${lang["langreaction"]})`,
        dataIndex: "rcolumn",
        key: "rcolumn",
      },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        fixed: "right",
        render: (txt: string, record: ITWorkbench) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    loading={delData?.id === record.id && delWorkbenchLoading}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];

    return (
      <Table
        dataSource={allWorkbench}
        columns={columns}
        bordered
        loading={allWorkbenchLoading}
      />
    );
  })
);

const Workbench: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  return (
    <>
      {/* 搜索和新增按钮组件 */}
      <SearchAddComp />

      {/* 工作台列表 */}
      <WorkbenchList />

      {/* 新增 编辑试剂瓶弹窗 */}
      <AddEditWorkbenchModal />
    </>
  );
};

export default inject("store")(observer(Workbench));
